import types from './types.js'
import store from './index.js'
import axios from 'axios'
import moment from 'moment'
import env from '@/config/env'
import {createSignData, creatSignWrap} from '@/myutl/utlenc'
import {apiGetSign} from '@/service/apiService'

const state = {
  isLocDev: false,      // 默认本地开发模式
  isActRet: false,      // 异步操作返回标志
  isRetSucc: false,
  retErrcd: null,
  retErrmsg: null,
  encDat: null,         // 加密后的数据
  storeAuthInf: {            // 授权信息
    authCode: null,
    authToken: null,
    authCodeTs: null,
    authTokenTs: null
  },
  hasAuthCode: false,
  hasAuthToken: false,
  authErrmsg: null,
  postionInf: {
    hasPostion: false,  // 初始未获取地址信息
    errmsg: null,
    lng: 0.0,           // 经度longitude
    lat: 0.0,           // 纬度latitude
    city: "",
    citycode: "",       // "021"
    district: "",       // "浦东新区"
    province: "",       // "上海市"
    street: "",         // "锦绣东路"
    streetNumber: "",   // "4819号"
    township: ""        // "唐镇"
  }
}

const getters = {
  isLocDev(state) {
    return state.isLocDev;
  },
  isActRet(state) {
    return state.isActRet;
  },
  retErrmsg(state) {
    return state.retErrmsg;
  },
  isRetSucc(state) {
    return state.isRetSucc;
  },
  getEncDat(state) {
    return state.encDat;e
  },
  hasAuthCode(state) {
    // return true;
    return state.hasAuthCode;
  },
  hasAuthToken(state) {
    return state.hasAuthToken;
  },
  authCode(state) {
    return state.storeAuthInf.authCode;
  },
  authToken(state) {
    return state.storeAuthInf.authToken;
  },
  postionInf(state) {
    return state.postionInf;
  },
  storeAuthInf(state) {
    return state.storeAuthInf;
  }
}

const actions = {
  initAction({commit, state}) {
    commit(types.ACTION_RET, {isRetSucc: false, errmsg: null});
  },
  async getAuthCode({commit, state}) {
    let params = {};

    let retData = await creatSignWrap(params);
    if (!retData.isRetSuss) {
      commit(types.LOGIN_USER, {isRetSucc: false, errmsg: retData.errmsg});
      return;
    }
    params.sign = retData.data;
    console.log("getAuthCode-params:", params);

    let uri = "/hr/userauthcode"
    axios.get(uri, {params}, {timeout: 100}).then(res => {
      retData = res.data;
      console.info("%s:", uri, retData);

      if (res.data.code !== "00000") {
        commit(types.GET_AUTHCODE, {isRetSucc:false, errcd:retData.code, errmsg:retData.msg});
      } else {
        commit(types.GET_AUTHCODE, {isRetSucc:true, authCode:retData.appAuthCode, authCodeTs:params.timestamp});
      }
    });
  },
  async getAuthToken({commit, state}, authCode) {
    let curTs = moment().format('YYYYMMDDHHmmss');
    let params = {
      "bizContent": {
        "appId": env.appId,
        "appAuthCode": authCode
      }
    };
    let retData = await creatSignWrap(params);
    if (!retData.isRetSuss) {
      commit(types.LOGIN_USER, {isRetSucc: false, errmsg: retData.errmsg});
      return;
    }
    params.sign = retData.data;
    console.log("getAuthToken-params:", params);

    let uri = "/hr/userauthtoken";
    axios.get(uri, {params}, {timeout: 100}).then(res => {
      retData = res.data;
      console.info("%s:", uri, retData);

      if (res.data.code !== "00000") {
        commit(types.GET_AUTHTOKEN, {isRetSucc:false, errcd: retData.subCode, errmsg:res.data.msg});
      } else {
        commit(types.GET_AUTHTOKEN, {isRetSucc:true, authToken:res.data.appAuthToken, authTokenTs:curTs});
      }
    });
  },
  createSign({commit, state}) {
    store.dispatch('initAction');
    let curTs = moment().format('YYYYMMDDHHmmss');
    let uri = "/api/createsign";    // 调用本地devServer进行签名操作
    axios.get(uri,
              {
                params:{
                  "appId": appId,
                  "charset": "utf-8",
                  "timestamp": curTs,
                  "version": "1.0"
                }
              }, {timeout: 100}).then(resp => {
      console.log(uri, "get.params:", resp.config.params);
      console.log(uri, resp.data);

      // if (resp.data.code !== "00000") {
      //   commit(types.GET_AUTHTOKEN, {isRetSucc:false, errmsg:resp.data.msg});
      // } else {
      //   commit(types.GET_AUTHTOKEN, {isRetSucc:true, authToken:resp.data.appAuthToken, authTokenTs:curTs});
      // }
    });
  },
  // 获取当前地理位置(信息保留在state.postionInf)
  getPosition({commit, state}) {
    console.log("getPosition");
    let mapObj = new AMap.Map('iCenter');
    mapObj.plugin('AMap.Geolocation', () => {
      let geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,   // 是否使用高精度定位，默认:true
        timeout: 3000,             // ms超过10秒后停止定位，默认：无穷大
        maximumAge: 0,              // 定位结果缓存0毫秒，默认：0
        convert: true,              // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
        showButton: true,           // 显示定位按钮，默认：true
        buttonPosition: 'LB',       // 定位按钮停靠位置，默认：'LB'，左下角
        buttonOffset:
          new AMap.Pixel(10, 20),   // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        showMarker: true,           // 定位成功后在定位到的位置显示点标记，默认：true
        showCircle: true,           // 定位成功后用圆圈表示定位精度范围，默认：true
        panToLocation: true,        // 定位成功后将定位到的位置作为地图中心点，默认：true
        zoomToAccuracy:true         // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      });
      mapObj.addControl(geolocation);
      geolocation.getCurrentPosition();

      AMap.event.addListener(geolocation, 'complete', (res) => {
        console.log("addressComponent:", res.addressComponent);
        let postionInf = {
          hasPostion: true,
          lng:res.position.lng,
          lat:res.position.lat,
          city: res.addressComponent.city,
          citycode: res.addressComponent.citycode,
          district: res.addressComponent.district,
          province: res.addressComponent.province,
          street: res.addressComponent.street,
          streetNumber: res.addressComponent.streetNumber,
          township: res.addressComponent.township
        };
        commit(types.GET_POSITION, postionInf);
      }); // 返回定位信息
      AMap.event.addListener(geolocation, 'error', (res) => {
        console.log("addListener");
        let postionInf = {
          hasPostion: false,
          errmsg: res
        };
        commit(types.GET_POSITION, {postionInf: postionInf});
      }); // 返回定位出错信息
    })
  }
}

const mutations = {
  [types.ACTION_RET](state, data){
    if (data.isRetSucc) {
      state.isRetSucc = true;
    } else {
      state.isRetSucc = false;
      state.retErrmsg = data.errmsg;
    }
  },
  [types.GET_AUTHCODE](state, data){
    if (data.isRetSucc) {
      state.hasAuthCode = true;
      state.storeAuthInf.authCode = data.authCode;
      state.storeAuthInf.authCodeTs = data.authCodeTs;
      // console.warn("authCode:", state.storeAuthInf.authCode);
    } else {
      state.hasAuthCode = false;
      state.authErrmsg = data.errmsg;
    }
    // console.log("hasAuthCode:", state.hasAuthCode);
    // console.log("storeAuthInf:", state.storeAuthInf);
  },
  [types.GET_AUTHTOKEN](state, data){
    if (data.isRetSucc) {
      state.hasAuthToken = true;
      state.storeAuthInf.authToken = data.authToken;
      state.storeAuthInf.authTokenTs = data.authTokenTs;
      console.log("authToken:", state.storeAuthInf.authToken);
    } else {
      state.hasAuthToken = false;
      state.authErrmsg = data.errmsg;
    }
    // console.log("hasAuthToken:", state.hasAuthToken);
    // console.log("storeAuthInf:", state.storeAuthInf);
    // console.log("store.getters.authToken:", store.getters.authToken);
  },
  [types.GET_POSITION](state, data) {
    console.log("data:", data);
    state.postionInf = data;
    console.log("state.postionInf:", state.postionInf);
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
